/**
 * 深度查询
 * @param tree
 * @param newTree
 * @param map
 */
export function DepthSearch(tree, newTree, map) {
    tree.forEach(item => {
        let node = {id: item.id, iconCls: item.iconCls, text: item.text, name: item.name}
        let active = map[item.id]
        if (active === 2) {  // 父节点
            node['state'] = 'open'
        }
        if (active === 1) {  // 子节点
            // node['state'] = 'open'
            node["selected"] = true
            node["nodeCls"] = 'tree-node-selected'
        }
        if (item.children) {
            node.children = []
            DepthSearch(item.children, node.children, map)
        }
        newTree.push(node)
    })
}

/**
 * 搜索查询数
 * @param node
 * @param id
 * @param map
 * @returns {boolean}
 */
export function SearchBinaryTree(node, id, map) {
    if (node === null) {
        return false
    }

    if (SearchBinaryTree(node.left, id, map)) {
        map[node.id] = 2
        return true
    }
    if (id === node.id) {
        map[node.id] = 1
        return true
    }
    if (SearchBinaryTree(node.right, id, map)) {
        return true
    }
}

/**
 * 处理成二叉查询数
 * @param tree
 * @returns {Node}
 */
export function BinaryTree(tree) {
    let roots = new Node(0, "root", tree)
    GenChildNode(roots)
    return roots
}

/**
 * 节点
 * @param id
 * @param value
 * @param children
 * @constructor
 */
function Node(id, value, children) {
    this.left = null
    this.right = null
    this.id = id
    this.value = value
    this.children = children
    this.hasChildren = function () {
        return children.length > 0
    }
}

/**
 *
 * @param N
 */
function GenChildNode(N) {
    let active;
    N.children.forEach((item, key) => {
        let node = new Node(item.id, item.text, item.children || [])
        if (key === 0) {
            N.left = node  // 设置第一个孩子为左子树
        } else {
            active.right = node
        }
        if (node.hasChildren()) {
            GenChildNode(node)
        }
        active = node
    })
}